import React, { createContext, useContext, useState, useEffect } from 'react'
import { authAPI } from '../services/api'

const AuthContext = createContext()

export const useAuth = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // 检查本地存储中的用户信息
    const savedUser = localStorage.getItem('user')
    const token = localStorage.getItem('token')
    
    if (savedUser && token) {
      try {
        setUser(JSON.parse(savedUser))
        
        // 验证token是否有效
        authAPI.getProfile()
          .then(response => {
            if (response.code === 200) {
              setUser(response.data)
              localStorage.setItem('user', JSON.stringify(response.data))
            } else {
              // Token无效，清除本地存储
              logout()
            }
          })
          .catch(() => {
            // Token无效，清除本地存储
            logout()
          })
          .finally(() => {
            setLoading(false)
          })
      } catch (error) {
        logout()
        setLoading(false)
      }
    } else {
      setLoading(false)
    }
  }, [])

  const login = async (credentials) => {
    try {
      const response = await authAPI.login(credentials)
      if (response.code === 200) {
        const { token, user } = response.data
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(user))
        setUser(user)
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '登录失败，请检查网络连接' 
      }
    }
  }

  const logout = async () => {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      setUser(null)
    }
  }

  const updateProfile = async (data) => {
    try {
      const response = await authAPI.updateProfile(data)
      if (response.code === 200) {
        setUser(response.data)
        localStorage.setItem('user', JSON.stringify(response.data))
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '更新失败' 
      }
    }
  }

  const changePassword = async (data) => {
    try {
      const response = await authAPI.changePassword(data)
      if (response.code === 200) {
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.message || '密码修改失败' 
      }
    }
  }

  const value = {
    user,
    loading,
    login,
    logout,
    updateProfile,
    changePassword,
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}